package cn.kinoko.service.email.impl;

import cn.kinoko.common.code.ErrorCodeEnum;
import cn.kinoko.common.utils.ExceptionUtil;
import cn.kinoko.model.email.Mail;
import cn.kinoko.service.email.EmailService;
import jakarta.annotation.Resource;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

/**
 * @author kk
 */
@Slf4j
@Service
public class EmailServiceImpl implements EmailService {

    @Resource
    private JavaMailSender javaMailSender;
    @Resource
    private TemplateEngine templateEngine;

    @Value("${spring.mail.username}")
    private String from;

    /**
     * 发送简单邮件
     *
     * @param mail 邮件信息
     * @return 发送结果
     */
    @Override
    public boolean sendMail(Mail mail) {
        try {
            MimeMessage mimeMessage = buildMimeMsg(mail);
            javaMailSender.send(mimeMessage);
            return true;
        } catch (Exception e) {
            log.error("[邮件发送] 失败", e);
            ExceptionUtil.throwOut(ErrorCodeEnum.SERVICE_ERROR_C0504);
        }
        return false;
    }

    /**
     * 构建MimeMessage
     *
     * @param mail 邮件信息
     * @return 信息
     * @throws MessagingException 异常
     */
    private MimeMessage buildMimeMsg(Mail mail) throws MessagingException {
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(javaMailSender.createMimeMessage(), mail.getAttachment() != null, "UTF-8");
        mimeMessageHelper.setFrom(from);
        mimeMessageHelper.setTo(mail.getTo());
        mimeMessageHelper.setSubject(mail.getSubject());
        mimeMessageHelper.setText(mail.getContent());
        // 添加附件
        if (mail.getAttachment() != null) {
            mimeMessageHelper.addAttachment(mail.getAttachmentName(), new ByteArrayResource(mail.getAttachment()));
        }
        // 添加模板
        if (mail.getTemplateParams() != null) {
            Context context = new Context();
            context.setVariables(mail.getTemplateParams());
            String process = templateEngine.process(mail.getTemplateName(), context);
            mimeMessageHelper.setText(process, true);
        }
        return mimeMessageHelper.getMimeMessage();
    }

}
